package com.shell.customer.base.rx;

import com.shell.bee.base.exception.UnCheckException;
import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.JsonUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.customer.base.CusEvent;
import com.shell.customer.base.service.CusAcctService;
import com.shell.customer.base.service.CusAcctUseService;
import com.shell.customer.base.vo.CusRecVo;
import com.shell.customer.po.CusAcct;
import com.shell.customer.po.CusAcctUse;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UpdateCusAcctSubscriber extends OnErrorNotImplementedSubscriber<CusEvent> {
	@Autowired
	private CusAcctService cusAcctService;
	@Autowired
	private CusAcctUseService cusAcctUseService;

	public void onApplicationEvent(CusEvent event) {
		CusRecVo cusVo = event.getCusRecVo();

		CusAcct cusAcct = null;
		try {
			cusAcct = (CusAcct) JsonUtil.fromJson(cusVo.getAcctInfo(), CusAcct.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new UnCheckException("������������������");
		}
		if (StringUtil.emptyAndNull(cusAcct.getAcctId())) {
			cusAcct.setAcctId(SystemUtil.getUUID());
			cusAcct.setAcctState("N");
			cusAcct.setAcctType("0");
			cusAcct.setCreateTime(DateUtil.getSystemDateTime());
			cusAcct.setCusId(cusVo.getCusId());
			cusAcct.setAcctName(cusVo.getCusName());
			this.cusAcctService.save(cusAcct);
		} else {
			CusAcct delAcct = (CusAcct) this.cusAcctService.selectByKey(cusAcct.getAcctId());
			if ((delAcct != null) && (!delAcct.getAcctNo().equals(cusAcct.getAcctNo()))) {
				delAcct.setAcctState("D");
				event.setDelCusAcct(delAcct);
			}
			this.cusAcctService.updateNotNull(cusAcct);
		}
		CusAcctUse acctUse = new CusAcctUse();
		acctUse.setAcctNo(cusAcct.getAcctNo());
		this.cusAcctUseService.deleteEntity(acctUse);
		acctUse.setUseCode("00");
		this.cusAcctUseService.saveOrUpdate(acctUse);

		event.setCusAcct(cusAcct);
	}
}
